package room;

import java.util.Map;
import java.util.TreeMap;

import common.ErrCode;
import user.User;

/**
 * 房间管理类
 */
public class RoomMgr {
    private static RoomMgr mgr = null;

    /**
     * 单例
     * 
     * @return
     */
    public static RoomMgr getInstance() {
        if (mgr == null) {
            mgr = new RoomMgr();
        }
        return mgr;
    }

    /**
     * 创建房间
     *
     * @return
     */
    public Room createRoom(int robotN) {
        mRoomCnt++;
        Room o = new Room(mRoomCnt, robotN);
        rooms.put(o.getID(), o);

        System.out.printf("roomMgr, create room:%d\n", o.getID());
        return o;
    }

    /**
     *
     * @param u      角色
     * @param roomId 房间id
     * @return
     */
    public int onEnterRoom(User u, int roomId) {
        int uRoomId = u.getRoomID();
        if (uRoomId != 0) {
            System.err.printf("roommgr enter:%d, user:%d, has in:%d\n", roomId, u.getID(), uRoomId);
            return ErrCode.ERR_ENTERROOM_HASIN;
        }

        Room o = rooms.get(roomId);
        if (o == null) {
            System.err.printf("roommgr enter:%d, user:%d room not exist\n", roomId, u.getID());
            return ErrCode.ERR_ENTERROOM_NOEXIST;
        }

        return o.onEnter(u);
    }

    /**
     *
     * @param u 角色
     * @return
     */
    public int onLeaveRoom(User u) {
        int uRoomId = u.getRoomID();
        if (uRoomId == 0) { // 这个判断可以省略 类似同
            System.err.printf("roommgr leave:%d, user:%d not in room\n", uRoomId, u.getID());
            return ErrCode.ERR_LEAVEROOM_NOTIN;
        }

        Room o = rooms.get(uRoomId);
        if (o == null) {
            System.err.printf("roommgr leave:%d, user:%d room not exist\n", uRoomId, u.getID());
            return ErrCode.ERR_LEAVEROOM_NEXIST;
        }

        return o.onLeave(u);
    }

    /**
     * 押注
     *
     * @param u   角色
     * @param bet 押注分
     * @return
     */
    public int onBet(User u, int idx, int score) {
        int uRoomId = u.getRoomID();
        if (uRoomId == 0) {
            System.err.printf("roommgr bet, user:%d, not in room\n", u.getID());
            return ErrCode.ERR_BET_NOTINROOM;
        }

        Room o = rooms.get(uRoomId);
        if (o == null) {
            System.err.printf("roommgr bet, user:%d room not exist:%d\n", u.getID(), uRoomId);
            return ErrCode.ERR_BET_ROOMNOXIST;
        }

        return o.onBet(u, idx, score);
    }

    /**
     * 所有房间定时器处理
     */
    public void onTimer() {
        rooms.forEach((rid, room) -> {
            //
            // System.out.println("roommgr ontimer");
            room.onTimer();
        });
    }

    private int mRoomCnt = 12; // 房间起始id
    private Map<Integer, Room> rooms // 房间列表 房间id-->
            = new TreeMap<>();
}
